$(function() {
	
    //绑定ICheck样式
	WASP_WIDGET.triggerICheck();
	//初始化表单校验和提交事件
	initValidateAndSubmit();	 
	//调用下拉列表美化方法带输入框
	bindQPrdCode();
	
	
	triggerValidOnSelectChange('instParentId');
	$("#instLevel").change(function () {
		var value =$("#instLevel").val();
		if('SUB' == value){
			$("#isShow").show();
			
			$("#instParentId").rules("add", {
				required: true, messages: {required: "父级机构不能为空"}
			});
			
		}else{
			$("#isShow").hide();
			$("#instParentId").rules("remove");
		}
	});
	
	initParentSelect2();
});

//下拉列表美化方法带输入框 
function bindQPrdCode(){
	 $('#instLevel').select2({
	        placeholder: '层级结构',
	        allowClear:false
	 });	 
	 $('#instType').select2({
	        placeholder: '机构类型',
	        allowClear:false
	 });
}

// 自定义当层级结构为子级时，父级机构不能为空校验
jQuery.validator.methods["requiredByLevel"]=(function(value,element){
	 var instLevel = $("#instLevel").val();//层级结构 
	 var instParentId = $("#instParentId").val();//父级机构
	 var flag =0;
	 if(1==instLevel){//当层级结构为子级时，父级机构必选
	    	if(null == instParentId || $.trim(instParentId) == ""){
	    		flag=1;	  
	    	}
	 }	
	if(flag==1){
		return false;
	}else{
		return true;
	}
});


//自定义当层级结构为子级时，父级机构不能为空校验
jQuery.validator.methods["requiredBy"]=(function(value,element,params){
	if($("#"+params[0]).val()!=params[1]){
		if(!value){
			return false;
		}
	}
	return true;
});



//初始化表单校验和提交事件
function initValidateAndSubmit(){
	 $("#institutionAddForm").validate({
	        focusCleanup: true,
	        rules: {
	            //需要验证的input/select id
	            //默认校验规则可以参考http://www.runoob.com/jquery/jquery-plugin-validate.html
	        	instSName: {
	                required: true,
	                checkIsExists:["instSName"]
	            }, 
	            instLevel:{
	            	required: true	
	            },
	            instType:{
	            	required: true
	            },	            
	            instLName: {
	                required: true,
	                checkIsExists:["instLName"]
	            }
	        },
	        messages: {
	        	instSName:{
	                required: "机构简称不能为空" , 
	                checkIsExists:"机构简称已存在，请重新输入"
	            },
	        	instLName:{
	                required: "机构全称不能为空" ,
	                checkIsExists:"机构全称已存在，请重新输入"
	            },
	            instType:{
	            	required: '机构类型不能为空',
	            },
	            instLevel:{
	            	required: '机构层级不能为空'
	            }
	        }
	    });
	 
}

function submitInstitutionAddForm() {
	SubmitAndPreventSecond("institutionAddForm",null);
	
}

function initParentSelect2(){
	$("#instParentId").select2({
		language : "zh-CN",
		multiple : false,
		placeholder: '请选择父级机构',
		initSelection: function(element, callback) {
			var $insParent = $("#instParentId");
            var data = {id: $insParent.attr("data-ins-id"), text: $insParent.attr("data-ins-name")};  
            callback(data);
		},
		ajax : {
			url : INSTITUTION_PATH + "/institutions.do",
			type : "POST",
			data : function(params) {
				var query;
				if (params.term == null || params.term == '' || params.term == 'undefind') {
					query = {
						name : "",
						limit : 10
					};
				} else {
					query = {
						name : params.term
					};
				}
				return query;
			},
			dataType : "json",
			processResults : function(data) {
				var results = $.map(data, function(obj) {
					return {
						id : obj.instId,
						text : obj.instSName
					}
				});
				return {
					results : results
				};
			}
		},
		cache : false,
		delay : 3000
	});
};
// 检验唯一性
jQuery.validator.methods["checkIsExists"]=(function(value,element,params){
	//验证是否重复，pass为false代表重复，校验不通过
	var pass = false;
	var instSName = null;
	var instLName = null;
	var instCode = null;
	// 根据类型赋值
	if(params[0] == 'instSName'){
		instSName =$.trim($('#instSName').val());
	}else if(params[0] == 'instLName'){
		instLName =$.trim($('#instLName').val());
	}else if(params[0] == 'instCode'){
		instCode =$.trim($('#instCode').val());
	}
	var instId = $("#instId").val();
	if(instId == null && instId == ''){
		instId = null;
	}
	if(!value)
		return true;
	
	$.ajax({
		  url: INSTITUTION_PATH+"/checkRepeat.do",
		  dataType: "json",
		  type: "POST",
		  cache: false,
		  async: false,
		  data: {
			  instId : instId,
			  instSName : instSName,
			  instLName : instLName,
			  instCode : instCode
		  },
		  success: function( data ) {
				if(data.object == true){
					pass = false;
					return;
				}
				pass=true;
		  },
		  error: function(jqXHR, textStatus, errorThrown){
				ctools.alert("查询失败" + textStatus);
				pass = false;
		  }
	});
	return this.optional(element) || pass;
});









